package com.mattgarner.jaddas.node.command.ddl;

import com.mattgarner.jaddas.dataset.DataSet;
import com.mattgarner.jaddas.node.DataSetManager;
import com.mattgarner.jaddas.node.RemoteClient;
import com.mattgarner.jaddas.node.command.CommandParser;
import com.mattgarner.jaddas.node.data.LocalTableDataProvider;
import com.mattgarner.jaddas.node.net.Protocol;
import com.mattgarner.jaddas.node.net.Worker;

public class CmdAlterDatasetAddIndex extends CommandParser {

	public CmdAlterDatasetAddIndex(Worker serverWorker, RemoteClient client) {
		super(serverWorker, client);
	}
	
	// ALTER DATASET ADD INDEX
	public final boolean parseCommand(String command) {
		Worker worker = getServerWorker();
		RemoteClient clientConfig = getRemoteClient();
		
		command = command.replaceAll("\\s+?", " ");
		String[] cmd = extractRegexGroups("(?i)^ALTER\\s+DATASET\\s+([A-Z0-9_\\.]+?)\\s+ADD\\s+INDEX\\s+ON\\s+([A-Z0-9_\\.,\\s]+?)\\s*$", command);
		
		String dsName;
		String dsColumns[];
		
		try { 
			dsName = cmd[0];
			dsColumns = cmd[1].split("\\s*,\\s*");
		} catch(RuntimeException e) {
			worker.sendMessage(Protocol.MSG_NAK, "Invalid parameters.");
			return true;
		}
		
		DataSetManager dsManager = DataSetManager.getInstance();
		DataSet dataSet = dsManager.getDataSetByName(dsName);
		
		if(dataSet == null) {
			worker.sendMessage(Protocol.MSG_NAK, "Dataset '" + dsName + "' does not exist.");
			return true;
		}
		
		// run bitmap index
		try {
			LocalTableDataProvider dsDataProvider = new LocalTableDataProvider(dataSet);
			dsDataProvider.addBitmapIndex(dsColumns);
			worker.sendMessage(Protocol.MSG_OK, "Added "+ dsColumns.length +" index(es) on '"+dsName+"'. (in "+calculateExecuteTime()+" secs.)");
			return true;
		} catch(Exception e) {
			worker.sendMessage(Protocol.MSG_NAK, "Exception: " + e.getMessage());
			return true;
		}

	}

}
